'use strict'
let { Sequelize, DataTypes } = require('sequelize');
let { database, username, password, host, dialect } = require('./connection');

let sequelize = new Sequelize(database, username, password, {
    host: host,
    dialect: dialect
})

function defaultModel(name, attrs) {
    let prop = {};
    prop.id = {
        type: DataTypes.BIGINT,
        primaryKey: true,
        autoIncrement: true
    }

    for (let key in attrs) {
        let value = attrs[key];
        prop[key] = value;
    }


    prop.createdAt = {
        type: DataTypes.BIGINT,
        allowNull: false
    }

    prop.updatedAt = {
        type: DataTypes.BIGINT,
        allowNull: false
    }

    prop.version = {
        type: DataTypes.BIGINT,
        allowNull: false
    }

    prop.remarks = {
        type: DataTypes.BIGINT,
        allowNull: true
    }

    let obj = sequelize.define(name, prop, {
        tableName: name,
        timestamps: false,
        hooks: {
            beforeValidate: function(obj) {
                let now = Date.now();
                if (obj.isNewRecord) {
                    obj.createdAt = now;
                    obj.updatedAt = now;
                    obj.version = 0;
                } else {
                    obj.updatedAt = now;
                    obj.version += 1;
                }
            }
        }
    });

    return obj;
}

let obj = {
    sequelize,
    defaultModel,
    DataTypes
};

module.exports = obj;